Simple Variance Sample


.NET Framework
Language Samples, Variance
Desktop
en-US
11/28/2011

The SimpleVariance sample program shows C# 4.0 support for covariance and contravariance when using generic types in delegates and interfaces. In C# 3.0 generic types were invariant. As a result, this sample compiles fine in C# 4.0, while it does not compile in previous versions of C#.

There program first declares two simple classes and two delegates:

class  Animal { }
class Cat : Animal { }

delegate T Func1<out T>();
delegate void Action1<in T>(T a);

It then implements the delegates and uses the classes:

Func1<Cat> cat = () => new Cat();
Action1<Animal> act1 = (ani) => { Console.WriteLine(ani); };

It then makes the assignments that requires covariant and contravariant support:

Func1<Animal> animal = cat;
Action1<Cat> cat1 = act1;

It is this latter set of assignments that work in C# 4.0 but not in previous versions of C#. The first assignment illustrates coveriance, and the second contravariance.

The new contextual keywords out and in allow you to specify whether a generic type is going to be passed into a delegate or interface method, or returned from a delegate or interface method.